<template>
  <!-- 外层卡片，标题“我的信息” -->
  <t-card title="我的信息" class="user-info-card" :bordered="false">
    <div class="user-info-main">
      <!-- 头像上传区域 -->
      <div
        class="avatar-upload"
        @mouseenter="showPlus = true"
        @mouseleave="showPlus = false"
        style="position: relative"
      >
        <!-- 头像图片 -->
        <t-avatar :image="localUserInfo.avatarUrl || defaultAvatar" size="180px" class="avatar-img" />
        <!-- 鼠标悬浮时显示的+号按钮，绝对定位在头像中央 -->
        <div v-show="showPlus" class="avatar-plus-btn" @click="triggerUpload">
          <span class="plus-icon">+</span>
        </div>
        <!-- 隐藏的input[type=file]，用于手动触发文件选择 -->
        <input ref="fileInputRef" type="file" accept="image/*" style="display: none" @change="onFileChange" />
      </div>
      <!-- 用户信息表格 -->
      <div class="user-info-table">
        <t-descriptions :column="1" layout="vertical">
          <t-descriptions-item label="账号">
            {{ localUserInfo.account || '-' }}
          </t-descriptions-item>
          <t-descriptions-item label="用户名">
            {{ localUserInfo.username || '-' }}
          </t-descriptions-item>
        </t-descriptions>
      </div>
      <!-- 新增：操作按钮区域 -->
      <div style="margin-top: 24px; display: flex; gap: 16px; justify-content: center">
        <!-- 修改账号按钮 -->
        <t-button @click="showEditAccount = true" theme="primary" variant="outline">修改账号</t-button>
        <!-- 修改用户名按钮 -->
        <t-button @click="showEditName = true" theme="primary" variant="outline">修改用户名</t-button>
        <!-- 修改密码按钮 -->
        <t-button @click="showEditPwd = true" theme="primary" variant="outline">修改密码</t-button>
      </div>
      <!-- 修改账号弹窗 -->
      <t-dialog
        v-model:visible="showEditAccount"
        header="修改账号"
        :footer="false"
        width="400px"
        :close-on-overlay-click="false"
      >
        <t-form
          @submit="onEditAccountSubmit"
          :rules="editAccountRules"
          :data="editAccountForm"
          ref="editAccountFormRef"
        >
          <t-form-item label="新账号" name="account">
            <t-input v-model="editAccountForm.account" placeholder="请输入新的账号" />
          </t-form-item>
          <div style="text-align: right; margin-top: 16px">
            <t-button theme="primary" type="submit">保存</t-button>
            <t-button style="margin-left: 8px" variant="outline" @click="showEditAccount = false">取消</t-button>
          </div>
        </t-form>
      </t-dialog>
      <!-- 修改用户名弹窗 -->
      <t-dialog
        v-model:visible="showEditName"
        header="修改用户名"
        :footer="false"
        width="400px"
        :close-on-overlay-click="false"
      >
        <t-form @submit="onEditNameSubmit" :rules="editNameRules" :data="editNameForm" ref="editNameFormRef" clo>
          <t-form-item label="新用户名" name="username">
            <t-input v-model="editNameForm.username" placeholder="请输入新的中文用户名" />
          </t-form-item>
          <div style="text-align: right; margin-top: 16px">
            <t-button theme="primary" type="submit">保存</t-button>
            <t-button style="margin-left: 8px" variant="outline" @click="showEditName = false">取消</t-button>
          </div>
        </t-form>
      </t-dialog>
      <!-- 修改密码弹窗 -->
      <t-dialog
        v-model:visible="showEditPwd"
        header="修改密码"
        :footer="false"
        width="400px"
        :close-on-overlay-click="false"
      >
        <t-form @submit="onEditPwdSubmit" :rules="editPwdRules" :data="editPwdForm" ref="editPwdFormRef">
          <!-- 隐藏的用户名字段，辅助浏览器识别 -->
          <input
            type="text"
            name="username"
            :value="localUserInfo.account"
            autocomplete="username"
            style="display: none"
            tabindex="-1"
            aria-hidden="true"
          />
          <t-form-item label="新密码" name="password">
            <t-input
              v-model="editPwdForm.password"
              type="password"
              placeholder="请输入新密码"
              autocomplete="new-password"
            />
          </t-form-item>
          <t-form-item label="请再次输入" name="confirmPassword">
            <t-input
              v-model="editPwdForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              autocomplete="new-password"
            />
          </t-form-item>
          <div style="text-align: right; margin-top: 16px">
            <t-button theme="primary" type="submit">保存</t-button>
            <t-button style="margin-left: 8px" variant="outline" @click="showEditPwd = false">取消</t-button>
          </div>
        </t-form>
      </t-dialog>
    </div>
  </t-card>
</template>

<script setup lang="ts">
// 引入所需依赖
import { useUserStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';
import { onActivated, ref, watch } from 'vue';

// 在顶部引入接口方法
import { getInfo, updateAccount, updatePassword, updateUsername } from '@/api/userController';
import { checkFileSize, commonFileUpload } from '@/utils/upload';
// 声明组件名
defineOptions({
  name: 'UserIndex',
});

// 默认头像图片
const defaultAvatar = 'https://ss0.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2279408239,3825398873&fm=253&gp=0.jpg';

// 控制+号显示的变量
const showPlus = ref(false); // 是否显示+号
const fileInputRef = ref(); // input[type=file]的ref

// 触发上传文件选择框的方法
const triggerUpload = () => {
  // 通过ref手动触发input[type=file]的点击
  fileInputRef.value && fileInputRef.value.click();
};

// 监听input[type=file]的change事件，选中文件后手动上传
const onFileChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (files && files.length > 0) {
    const file = files[0];

    // 检查文件大小
    if (!checkFileSize(file, 5, true)) {
      // 清空input值
      (e.target as HTMLInputElement).value = '';
      return;
    }

    const result = await commonFileUpload(file, true, (url: string) => {
      // 更新本地用户信息
      localUserInfo.value.avatarUrl = url;
      // 更新用户信息
      userStore.userInfo.avatarUrl = url;
      MessagePlugin.success('头像上传成功');
    });

    // 处理上传失败的情况
    if (result.status === 'fail') {
      MessagePlugin.error('网络异常，头像上传失败');
    }

    // 清空input值，避免同一文件无法重复上传
    (e.target as HTMLInputElement).value = '';
  }
};

// 获取用户信息
const userStore = useUserStore();
// 创建本地用户信息响应式数据，用于存储从接口获取的最新数据
const localUserInfo = ref({
  account: '',
  username: '',
  avatarUrl: '',
});

// 组件挂载时获取最新的用户信息
onActivated(async () => {
  console.log('onActivated');
  try {
    const response = await getInfo();
    // 更新本地用户信息
    localUserInfo.value = response.data.data || {};
    // 更新存储的用户信息
    userStore.userInfo = response.data.data;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    MessagePlugin.error('获取用户信息失败');
  }
});

// 弹窗显示控制变量
const showEditName = ref(false); // 控制修改用户名弹窗显示
const showEditPwd = ref(false); // 控制修改密码弹窗显示
const showEditAccount = ref(false); // 控制修改账号弹窗显示

// 监听弹窗显示，重置表单内容
watch(showEditName, (val) => {
  if (val) {
    // 打开弹窗时清空用户名输入
    editNameForm.value.username = '';
  }
});
watch(showEditPwd, (val) => {
  if (val) {
    // 打开弹窗时清空密码输入
    editPwdForm.value.password = '';
    editPwdForm.value.confirmPassword = '';
  }
});
watch(showEditAccount, (val) => {
  if (val) {
    // 打开弹窗时清空账号输入
    editAccountForm.value.account = '';
  }
});

// 修改用户名表单及校验
const editNameForm = ref({ username: '' });
const editNameFormRef = ref();
const editNameRules = {
  username: [
    { required: true, message: '用户名不能为空', type: 'error' as const },
    {
      // 只校验为中文，不限制长度
      validator: (val: string) => {
        const valid = /^[\u4e00-\u9fa5]+$/.test(val);
        return valid ? true : { result: false, message: '用户名必须为中文', type: 'error' as const };
      },
      message: '用户名必须为中文',
      type: 'error' as const,
    },
  ],
};
// 修改用户名提交
const onEditNameSubmit = async () => {
  const validateResult = await editNameFormRef.value.validate();
  if (validateResult !== true) {
    return;
  }
  try {
    await updateUsername(editNameForm.value.username);
    // 重新获取最新的用户信息
    const response = await getInfo();
    localUserInfo.value.username = response.data.data.username;
    // 更新用户信息
    userStore.userInfo.username = response.data.data.username;
    MessagePlugin.success('用户名修改成功');
    showEditName.value = false;
  } catch (e: any) {
    MessagePlugin.error(e.message || '用户名修改失败');
  }
};

// 新增：修改账号表单及校验
const editAccountForm = ref({ account: '' });
const editAccountFormRef = ref();
const editAccountRules = {
  account: [
    { required: true, message: '账号不能为空', type: 'error' as const },
    {
      // 校验账号只能包含字母和数字
      validator: (val: string) => {
        const valid = /^[A-Za-z0-9]+$/.test(val);
        return valid ? true : { result: false, message: '账号只能由字母和数字组成', type: 'error' as const };
      },
      message: '账号只能由字母和数字组成',
      type: 'error' as const,
    },
  ],
};
// 修改账号提交
const onEditAccountSubmit = async () => {
  const validateResult = await editAccountFormRef.value.validate();
  console.log('validateResult', validateResult);
  if (validateResult !== true) {
    return;
  }
  try {
    await updateAccount(editAccountForm.value.account);
    MessagePlugin.success('账号修改成功');
    showEditAccount.value = false;
    // 重新获取最新的用户信息
    const response = await getInfo();
    localUserInfo.value.account = response.data.data.account;
    userStore.userInfo.account = response.data.data.account;
  } catch (e: any) {
    MessagePlugin.error(e.message || '账号修改失败');
  }
};

// 新增：修改密码表单及校验
const editPwdForm = ref({ password: '', confirmPassword: '' });
const editPwdFormRef = ref();
const editPwdRules = {
  password: [
    { required: true, message: '密码不能为空', type: 'error' as const },
    {
      validator: (val: string) => {
        // 校验密码长度为6-20位
        if (val.length < 6 || val.length > 20) {
          return { result: false, message: '密码长度必须在6到20位', type: 'error' as const };
        }
        // 校验只能为字母或数字
        if (!/^[A-Za-z0-9]+$/.test(val)) {
          return { result: false, message: '密码只能由字母或数字组成', type: 'error' as const };
        }
        return true;
      },
      type: 'error' as const,
    },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', type: 'error' as const },
    {
      validator: (val: string) => {
        // 校验两次输入一致
        if (val !== editPwdForm.value.password) {
          return { result: false, message: '两次输入的密码不一致', type: 'error' as const };
        }
        return true;
      },
      type: 'error' as const,
    },
  ],
};
// 修改密码提交
const onEditPwdSubmit = async () => {
  const validateResult = await editPwdFormRef.value.validate();
  if (validateResult !== true) {
    return;
  }
  try {
    // 直接传递字符串参数
    await updatePassword(editPwdForm.value.password);
    MessagePlugin.success('密码修改成功');
    showEditPwd.value = false;
    // 清空表单
    editPwdForm.value.password = '';
    editPwdForm.value.confirmPassword = '';
  } catch (e: any) {
    MessagePlugin.error(e.message || '密码修改失败');
  }
};
</script>

<style lang="less" scoped>
.user-info-card {
  max-width: 500px;
  margin: 40px auto;
  padding: 32px 24px;
}
.user-info-main {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-upload {
  position: relative; // 使+号绝对定位于头像区域
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}
.avatar-img {
  margin-bottom: 16px;
  border: 2px solid #f0f0f0;
  // 让头像容器成为定位参考
  position: relative;
}
.user-info-table {
  width: 100%;
  max-width: 350px;
}
.avatar-plus-btn {
  // 绝对定位在头像正中央
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 80px; // 加号按钮更大
  height: 80px;
  background: rgba(0, 0, 0, 0.5); // 半透明黑色背景
  color: #fff;
  font-size: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 2;
  transition: opacity 0.2s;
  opacity: 0.9;
  user-select: none;
  // 只在头像区域上方
  pointer-events: auto;
}
.plus-icon {
  display: block;
  font-size: 48px; // 加号字体更大
  line-height: 1;
}
</style>
